/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.geotools.tutorial;

import com.vividsolutions.jts.geom.Geometry;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFactorySpi;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.collection.AbstractFeatureVisitor;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.Feature;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;

/**
 *
 * @author oleg
 */
public class DirectionImprovement {
    SimpleFeatureCollection collection;

    private SimpleFeatureSource featureSource;

    public void add(SimpleFeature f){
        try {
            collection.add(f);
            System.out.println("start----");
            collection.accepts(new AbstractFeatureVisitor() {

                @Override
                public void visit(Feature feature) {
                    System.out.println((SimpleFeature)feature.getProperty("ID").getValue()+"");
                }
            }, null);
            System.out.println("finish---- collection size is "+collection.size());
        } catch (IOException ex) {
            Logger.getLogger(DirectionImprovement.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public DirectionImprovement(SimpleFeatureSource featureSource) {
        collection=FeatureCollections.newCollection();
        this.featureSource=featureSource;
    }

    public void save(){
        try {
            SimpleFeatureType schema = featureSource.getSchema();
            JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
            chooser.setDialogTitle( "Save reprojected shapefile");
            int returnVal = chooser.showSaveDialog(null);
            if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
                return;
            }
            File file = chooser.getSelectedFile();
            CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
            CoordinateReferenceSystem worldCRS = CRS.decode("EPSG:32637");
            boolean lenient = true; // allow for some error due to different datums
            SimpleFeatureCollection featureCollection = featureSource.getFeatures();
            DataStoreFactorySpi factory = new ShapefileDataStoreFactory();
            Map<String, Serializable> create = new HashMap<String, Serializable>();
            create.put("url", file.toURI().toURL());
            create.put("create spatial index", Boolean.TRUE);
            DataStore dataStore = factory.createNewDataStore(create);
            SimpleFeatureType featureType = SimpleFeatureTypeBuilder.retype(schema, worldCRS);
            dataStore.createSchema(featureType);
            Transaction transaction = new DefaultTransaction("Reproject");
            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(featureType.getTypeName(), transaction);
            SimpleFeatureIterator iterator = featureCollection.features();
            Object[] collectionArray = collection.toArray();
            long ids[]=new long[collection.size()];
            int k=0;
            Iterator<SimpleFeature> iterator1 = collection.iterator();
            while(iterator1.hasNext()){
                SimpleFeature next = iterator1.next();
                ids[k]=(Long)next.getProperty("ID").getValue();
                System.out.println(ids[k]+";"+next.getID());
                k++;
            }
            System.out.println("begin saving... k="+k);
            try {
                while (iterator.hasNext()) {
                    // copy the contents of each feature and transform the geometry
                    SimpleFeature feature = iterator.next();
                    boolean finded=false; k=0;
                    while((!finded) && (k<ids.length)){
                        if(((Long)(feature.getProperty("ID").getValue())).equals(ids[k])){
                            System.out.println(" !charley "+feature.getProperty("ID").getValue()+ "-"+ids[k]);
                            SimpleFeature copy = writer.next();
                            copy.setAttributes(feature.getAttributes());
                            Iterator<SimpleFeature> iterator2 = collection.iterator();
                            SimpleFeature next=(SimpleFeature) collectionArray[k];
                            
                            Geometry geometry = (Geometry) next.getDefaultGeometry();
                            copy.setDefaultGeometry(geometry);
                            writer.write();
                            finded=true;
                        }
                        if((k==ids.length-1)&&(!finded)){
                            System.out.println("оригинал "+feature.getProperty("ID").getValue()+ "-"+ids[k]);
                            SimpleFeature copy = writer.next();
                            copy.setAttributes(feature.getAttributes());
                            Geometry geometry = (Geometry) feature.getDefaultGeometry();
                            copy.setDefaultGeometry(geometry);
                            writer.write();
                        }
                        k++;
                    }
                }
                
                transaction.commit();
                JOptionPane.showMessageDialog(null, "Export to shapefile complete");
            } catch (Exception problem) {
                problem.printStackTrace();
                transaction.rollback();
                JOptionPane.showMessageDialog(null, "Export to shapefile failed");
            } finally {
                writer.close();
                iterator.close();
                transaction.close();
            }
        } catch (FactoryException ex) {
            Logger.getLogger(DirectionImprovement.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DirectionImprovement.class.getName()).log(Level.SEVERE,null, ex);
        }
    

    }


}
